package org.kassa.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.kassa.model.Arrival;
import org.kassa.model.Item;

public class ArrivalDaoImpl implements ArrivalDao{
	
	@Override
	public boolean acceptItem(Item item){
            try {
		String sql = "UPDATE items SET quantity=quantity + ? WHERE code = ?";
		PreparedStatement ps = DaoHelperImpl.getPreparedStatement(sql);
		ps.setInt(1, item.getQuantity());
		ps.setInt(2, item.getCode());
                
		if (ps.executeUpdate() == 1) {
			if (registerArrival(new Arrival(item)))	return true;
		}
            }
            catch (SQLException e) {
                org.kassa.service.Logger.log("SQLException caught");
                e.printStackTrace();
            }
            return false;
	}
	
	private boolean registerArrival(Arrival arrival) {
        try {
            String sql = "INSERT INTO arrivals (itemid, itemname, quantity, date) VALUES (?, ?, ?, ?)";
            PreparedStatement ps = DaoHelperImpl.getPreparedStatement(sql);
            ps.setInt(1, arrival.getItem().getId());
            ps.setString(2, arrival.getItem().getName());
            ps.setInt(3, arrival.getItem().getQuantity());
            ps.setTimestamp(4, arrival.getDate());
            if (ps.executeUpdate() == 1) return true;
            
            } catch (SQLException e) {
                org.kassa.service.Logger.log("SQLException caught");
                e.printStackTrace();
            }
        return false;
	}
        
}
